﻿Imports System.Data.SqlClient
Imports System.String
Imports DevExpress.XtraReports.UI

Public Class frmNuevoAnalisi
    Dim numero As Integer
    Public RnpPaciente As String
    Private Sub frmNuevoAnalisi_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: esta línea de código carga datos en la tabla 'LabCDMDataSet.SP_ListarDoctores' Puede moverla o quitarla según sea necesario.
        Me.SP_ListarDoctoresTableAdapter.Fill(Me.LabCDMDataSet.SP_ListarDoctores)
        'TODO: esta línea de código carga datos en la tabla 'LabCDMDataSet.Paciente' Puede moverla o quitarla según sea necesario.
        Me.PacienteTableAdapter.Fill(Me.LabCDMDataSet.Paciente)
        Me.dtpFechaEntrega.EditValue = Date.Today.Date
        If RnpPaciente <> Nothing Then
            Me.cboPaciente.EditValue = RnpPaciente
        End If
    End Sub

    Private Async Sub cboPaciente_EditValueChanged(sender As Object, e As EventArgs) Handles cboPaciente.EditValueChanged
        Try
            If varConexion.State = ConnectionState.Open Then
                varConexion.Close()
            End If

            Await varConexion.OpenAsync()

            Dim sqlCargarDatos As String = String.Format("SELECT a.Rnp_Paciente, a.Nombres, a.Apellidos, a.Fecha_Nacimiento, b.Sexo, a.Telefono, c.Tipo_Paciente FROM Paciente a INNER JOIN Sexo b ON a.Id_Sexo = b.Id_Sexo INNER JOIN Tipo_Paciente c ON a.Id_Tipo_Paciente = c.Id_Tipo_Paciente WHERE Rnp_Paciente = '{0}'", Me.cboPaciente.EditValue)

            Dim cmd As New SqlCommand(sqlCargarDatos, varConexion)
            Dim reader As SqlDataReader = Await cmd.ExecuteReaderAsync()

            If Await reader.ReadAsync() Then
                Me.txtNombres.EditValue = reader.Item("Nombres")
                Me.txtApellidos.EditValue = reader.Item("Apellidos")
                Me.txtEdad.EditValue = CInt(DateDiff(DateInterval.Month, CDate(reader.Item("Fecha_Nacimiento")), Date.Today.Date) / 12)
                Me.txtSexo.EditValue = reader.Item("Sexo")
                Me.txtTelefono.EditValue = reader.Item("Telefono")
                Me.txtTipoPaciente.EditValue = reader.Item("Tipo_Paciente")
            Else
                MessageBox.Show("No se ha encontrado este paciente.", varTitulo, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub chkSangre_CheckedChanged(sender As Object, e As EventArgs) Handles chkSangre.CheckedChanged
        If chkSangre.CheckState = CheckState.Checked Then
            Me.tmSangre.Enabled = True
        Else
            Me.tmSangre.Enabled = False
        End If
    End Sub

    Private Sub chkOrina_CheckedChanged(sender As Object, e As EventArgs) Handles chkOrina.CheckedChanged
        If chkOrina.CheckState = CheckState.Checked Then
            Me.tmOrina.Enabled = True
        Else
            Me.tmOrina.Enabled = False
        End If
    End Sub

    Private Sub chkHeces_CheckedChanged(sender As Object, e As EventArgs) Handles chkHeces.CheckedChanged
        If chkHeces.CheckState = CheckState.Checked Then
            Me.tmHeces.Enabled = True
        Else
            Me.tmHeces.Enabled = False
        End If
    End Sub

    Private Sub chkOtros_CheckedChanged(sender As Object, e As EventArgs) Handles chkOtros.CheckedChanged
        If chkOtros.CheckState = CheckState.Checked Then
            Me.tmOtros.Enabled = True
        Else
            Me.tmOtros.Enabled = False
        End If
    End Sub

    Private Sub btnGuardar_Click(sender As Object, e As EventArgs) Handles btnGuardar.Click
        If Me.cboPaciente.Text <> "[Vacío]" And Me.cboDoctor.Text <> "[Vacío]" Then
            GenerarCodAnalisis()

            Try
                If varConexion.State = ConnectionState.Open Then
                    varConexion.Close()
                End If
                varConexion.Open()
                Dim hAhora As DateTime = Convert.ToDateTime(Date.Now)
                Dim hSangre As DateTime = Convert.ToDateTime(Me.tmSangre.EditValue)
                Dim hOrina As DateTime = Convert.ToDateTime(Me.tmOrina.EditValue)
                Dim hHeces As DateTime = Convert.ToDateTime(Me.tmHeces.EditValue)
                Dim hOtros As DateTime = Convert.ToDateTime(Me.tmOtros.EditValue)
                Dim hEntrega As DateTime = Convert.ToDateTime(Me.tmHoraEntrega.EditValue)
                Dim cSangre, cOrina, cHeces, cOtros As Integer
                Dim tehora As String = hAhora.ToString("HH:mm")
                Dim tesangre As String = hSangre.ToString("HH:mm")
                Dim teorina As String = hOrina.ToString("HH:mm")
                Dim teheces As String = hHeces.ToString("HH:mm")
                Dim teotros As String = hOtros.ToString("HH:mm")
                Dim teentrega As String = hEntrega.ToString("HH:mm")

                If chkSangre.Checked = True Then
                    cSangre = 1
                Else
                    cSangre = 0
                End If
                If chkOrina.Checked = True Then
                    cOrina = 1
                Else
                    cOrina = 0
                End If
                If chkHeces.Checked = True Then
                    cHeces = 1
                Else
                    cHeces = 0
                End If
                If chkOtros.Checked = True Then
                    cOtros = 1
                Else
                    cOtros = 0
                End If


                Dim fechaHoy As DateTime = Date.Today
                Dim fechaHoy2 As String = fechaHoy.ToString("MM/dd/yyyy")
                Dim correlativo As String = Date.Today.Year & numero.ToString("00000")

                Dim sqlGuardar As String = String.Format("INSERT INTO Analisis (Fecha_Recepcion, Hora_Recepcion, Rnp_Paciente, Id_Medico, Muestra_Sangre, Hora_Toma_Sangre, Muestra_Orina, Hora_Toma_Orina, Muestra_Heces, Hora_Toma_Heces, Otros, Hora_Toma_Otros, Descripcion_Otros, Fecha_Entrega, Hora_Entrega, Observaciones, Codigo_Usuario, NumAnalisis) VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', '{14}', '{15}', {16}, '{17}')", fechaHoy2, tehora, Me.cboPaciente.EditValue, Me.cboDoctor.EditValue, cSangre, tesangre, cOrina, teorina, cHeces, teheces, cOtros, teotros, Me.txtAnalisisSolicitado.EditValue, Me.dtpFechaEntrega.DateTime.ToString("MM/dd/yyyy"), teentrega, Me.txtObservaciones.EditValue, 1, correlativo)

                Dim cmdGuardar As New SqlCommand(sqlGuardar, varConexion)

                cmdGuardar.ExecuteNonQuery()

                Dim resp As String = MessageBox.Show("Se ha guardado el análisis, ¿Desea imprimir un comprobante?", varTitulo, MessageBoxButtons.YesNo, MessageBoxIcon.Information)


                varConexion.Close()

                If resp = vbYes Then
                    Dim rptAnalisis As New rptNuevoAnalisis
                    rptAnalisis.LlenarDatos()
                    Dim reportTool As New ReportPrintTool(rptAnalisis)
                    reportTool.Report.CreateDocument(False)
                    reportTool.ShowRibbonPreviewDialog()
                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
    End Sub

    Private Sub GenerarCodAnalisis()
        Try
            If varConexion.State = ConnectionState.Open Then
                varConexion.Close()
            End If
            varConexion.Open()

            Dim sql As String = String.Format("SELECT COUNT(*) AS Total FROM Analisis WHERE YEAR(Fecha_Recepcion) = '{0}'", Date.Today.Year)
            Dim cmd As New SqlCommand(sql, varConexion)
            Dim reader As SqlDataReader = cmd.ExecuteReader

            If reader.Read Then
                If CInt(reader.Item("Total")) = 0 Then
                    numero = 1
                Else
                    numero = CInt(reader.Item("Total"))
                End If
            End If

            varConexion.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub btnCerrar_Click(sender As Object, e As EventArgs) Handles btnCerrar.Click
        Me.Dispose()
        Me.Close()
    End Sub
End Class